package core

import (
	"context"
	"github.com/go-redis/redis/v8"
	"github.com/sirupsen/logrus"
	"time"
	"wecom_rebot/common"
)

func ConnectRedis() *redis.Client {
	return InitRedis(0)
}

func InitRedis(db int) *redis.Client {
	redisConfig := common.Config.Redis
	rdb := redis.NewClient(&redis.Options{
		Addr:     redisConfig.Addr(),
		Password: redisConfig.Password,
		DB:       db,
		PoolSize: redisConfig.PoolSize,
	})

	_, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer cancel()
	_, err := rdb.Ping(context.Background()).Result()
	if err != nil {
		logrus.Errorf("redis 连接失败 %s", redisConfig.Addr())
		return nil
	}
	return rdb
}
